//
//  SettingVC.m
//  easyTaxi
//
//  Created by ellenpage on 12-12-11.
//  Copyright (c) 2012年 ellenpage. All rights reserved.
//

#define kIsReadAddress @"isReadAddress"
#define kIsReadSetting @"isReadSetting"

#import "Constant.h"
#import "SettingVC.h"
#import "PassValueClass.h"
#import "CustomActionSheet.h"
#import "RequestCMD.h"
#import "SocketObject.h"

BOOL userEnable;

@interface SettingVC ()<UINavigationControllerDelegate,UITabBarControllerDelegate,UIPickerViewDelegate,UIPickerViewDataSource,UIAlertViewDelegate,MFMessageComposeViewControllerDelegate>

@property (retain, nonatomic) NSArray *dataArray;
@property (retain, nonatomic) NSArray *savedArray;//服务器保存的数据

@property (retain, nonatomic) SettingVC *settingVC;

@property (weak, nonatomic) IBOutlet UITextField *phoneTxtField;
@property (weak, nonatomic) IBOutlet UIImageView *phoneImgView;
@property (weak, nonatomic) IBOutlet UITextField *nameTxtField;

@property (retain, nonatomic) NSArray *sexDataArray;
@property (retain, nonatomic) NSArray *arrangeDataArray;

@property (retain, nonatomic) UIPickerView *sexPicker;
@property (retain, nonatomic) UIPickerView *arrangePicker;

@property (weak, nonatomic) IBOutlet UIButton *sexBtn;
@property (weak, nonatomic) IBOutlet UIButton *arrangeBtn;

@property (retain, nonatomic) NSString *sexIdentifierStr;
@property (retain, nonatomic) NSString *arrangeStr;

- (IBAction)goBack;
- (IBAction)resignKeyboard;
- (IBAction)chooseSex;
- (IBAction)chooseArrange;
- (IBAction)sendToServer;

@end

@implementation SettingVC

#pragma mark - GoBack - 返回

- (IBAction)goBack
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}

#pragma mark - System Function - 系统函数

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [self loadData];//加载数据
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setPhoneTxtField:nil];
    [self setNameTxtField:nil];
    [self setPhoneImgView:nil];
    [self setSexBtn:nil];
    [self setArrangeBtn:nil];
    [super viewDidUnload];
}

#pragma mark - LoadData - 加载数据

- (void)loadData
{
    NSString *phoneStr   = [PassValueClass sharedIntance].teleNumStr;
    NSString *nameStr    = [PassValueClass sharedIntance].nickNameStr;
    NSString *sexStr     = [PassValueClass sharedIntance].sexStr;    
    NSString *arrangeStr = [PassValueClass sharedIntance].arrangeStr;
        
    _sexDataArray = [NSArray arrayWithObjects:@"男",@"女", nil];
    _arrangeDataArray =[NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"15",@"20",@"30",@"40",@"50",@"60",nil];

    if (phoneStr != nil) {
        _phoneTxtField.text = phoneStr;
        if ([[PassValueClass sharedIntance].isBindedStr isEqualToString:@"1"])
        {
            _phoneTxtField.userInteractionEnabled = NO;
        }
        
        [_phoneImgView setImage:[UIImage imageNamed:@""]];
    }
    else
    {
        [_phoneImgView setImage:[UIImage imageNamed:@""]];
    }
    
    if (![nameStr isEqualToString:nil])
    {
        _nameTxtField.text = nameStr;
    }
    else
    {
        _nameTxtField.text = @"E打车用户";
    }
    
    if ([sexStr isEqualToString:nil]) {
        [_sexBtn setTitle:sexStr forState:UIControlStateNormal];
    }
    else
    {
        [_sexBtn setTitle:@"男" forState:UIControlStateNormal];
        _sexIdentifierStr = @"2";
    }
    
    if ([arrangeStr isEqualToString:nil])
    {
        [_arrangeBtn setTitle:arrangeStr forState:UIControlStateNormal];
    }
    else
    {
        [_arrangeBtn setTitle:@"1" forState:UIControlStateNormal];
        _arrangeStr = @"1";
    }
}

- (IBAction)resignKeyboard//退键盘
{
    [_phoneTxtField   resignFirstResponder];
    [_nameTxtField    resignFirstResponder];
}

#pragma mark - UIPickerViewDataSource - PickerView数据源代理

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{    
    if (pickerView == _sexPicker)
    {
        return [_sexDataArray count];
    }
    
    if (pickerView == _arrangePicker)
    {
        return [_arrangeDataArray count];
    }
    return 0;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{    
    if (pickerView == _sexPicker)
    {
        return [_sexDataArray objectAtIndex:row];
    }
    
    if (pickerView == _arrangePicker)
    {
        return [_arrangeDataArray objectAtIndex:row];
    }
    return nil;
}

#pragma mark - UIPickerViewDelegate - PickerView代理


-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (pickerView == _sexPicker)
    {
        NSString *selected=[_sexDataArray objectAtIndex:row];
        [_sexBtn setTitle:selected forState:UIControlStateNormal];
        if ([selected isEqualToString:@"男"])
        {
            _sexIdentifierStr = @"2";
        }
        else if([selected isEqualToString:@"女"])
        {
            _sexIdentifierStr = @"1";
        }
        [self dismissModalViewControllerAnimated:YES];
        
    }
    if (pickerView == _arrangePicker)
    {
        NSString *selected=[_arrangeDataArray objectAtIndex:row];
        [_arrangeBtn setTitle:selected forState:UIControlStateNormal];
        if (selected != nil)
        {
            _arrangeStr = selected;
        }
        [self dismissModalViewControllerAnimated:YES];
    }
}

#pragma mark - UserInteraction - 用户交互

- (IBAction)chooseSex
{
    CustomActionSheet *sheet = [[CustomActionSheet alloc] initWithHeight:284.0f
                                                          WithSheetTitle:@"选择您的性别"];
    
    sheet.backgroundColor = [UIColor darkTextColor];
    
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0,50, 320, 50)];
    // label.text = @"这里是要自定义放的控制";
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = UITextAlignmentCenter;
    [sheet.view addSubview:label];
    [sheet showInView:self.view];
    
    _sexPicker=[[UIPickerView alloc]initWithFrame:CGRectZero];
    _sexPicker.autoresizingMask=UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    CGRect pickerFrame=CGRectMake(80,50,150,200);
    _sexPicker.frame=pickerFrame;
    _sexPicker.delegate=self;
    _sexPicker.dataSource=self;
    _sexPicker.showsSelectionIndicator=YES;
    
    [sheet addSubview:_sexPicker];   
}

- (IBAction)chooseArrange
{
    CustomActionSheet *sheet = [[CustomActionSheet alloc] initWithHeight:284.0f
                                                          WithSheetTitle:@"选择您的搜索范围"];
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(0,50, 320, 50)];
    // label.text = @"这里是要自定义放的控制";
    label.backgroundColor = [UIColor clearColor];
    label.textAlignment = UITextAlignmentCenter;
    [sheet.view addSubview:label];
    [sheet showInView:self.view];
        
    _arrangePicker=[[UIPickerView alloc] initWithFrame:CGRectZero];
    _arrangePicker.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    CGRect pickerFrame = CGRectMake(80,50,150,200);
    _arrangePicker.frame=pickerFrame;
    _arrangePicker.delegate=self;
    _arrangePicker.dataSource=self;
    _arrangePicker.showsSelectionIndicator=YES;
    
    [sheet addSubview:_arrangePicker];   
}

- (IBAction)sendToServer
{
    [self userLimits];
    
    if (userEnable == YES)
    {
    NSString *phoneStr = _phoneTxtField.text;
    NSString *nameStr  = _nameTxtField.text;
        
    if (nameStr == nil || _sexIdentifierStr == nil || _arrangeStr == nil || phoneStr == nil)
    {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"填写完整资料"
                                                     message:@"为了您和司机的方便，请您填写完整的资料，谢谢"
                                                    delegate:self
                                           cancelButtonTitle:@"我知道了"
                                           otherButtonTitles:nil];
        [alert show];
    }
    else if ([phoneStr length] != 11)
    {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"电话填写错误"
                                                     message:@"请填写正确的电话号码"
                                                    delegate:self
                                           cancelButtonTitle:@"我知道了"
                                           otherButtonTitles:nil];
        
        [alert show];
    }
    else if (nameStr != nil && _sexIdentifierStr != nil && _arrangeStr != nil && [phoneStr length] == 11)
    {
        [PassValueClass sharedIntance].teleNumStr  = phoneStr;
        [PassValueClass sharedIntance].nickNameStr = nameStr ;
        [PassValueClass sharedIntance].sexStr      = _sexIdentifierStr;
        [PassValueClass sharedIntance].arrangeStr  = _arrangeStr;
        
        NSString *string    = [RequestCMD requestCMD:kUserSetting];
        NSMutableData *data = [RequestCMD getWantedData:string];
        [[SocketObject sharedInstance].gcdSocket writeData:data withTimeout:-1 tag:kUserSetting];//socket写入数据
    }
    }
}


#pragma mark - 用户权限管理

- (void)userLimits
{
    if (!isSokectOk)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"服务器未连接,请稍后重试"
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        userEnable = NO;
        return;
    }
    
    if (!isAvaliableCityOk)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"你所在的区域不支持我们的服务,敬请期待~"
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        userEnable = NO;
        return;
    }

    
    if (!isLoginOk)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"网络问题导致登录异常,请稍后重试"
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        userEnable = NO;
        return;
    }
    
    //3.判断是否已经绑定手机号
    NSString *isBindedStr = [PassValueClass sharedIntance].isBindedStr;
    if (isBindedStr == nil)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"正在获取个人信息请稍后..."
                                                        message:nil
                                                       delegate:self
                                              cancelButtonTitle:@"好的"
                                              otherButtonTitles:nil, nil];
        [alert show];
        userEnable = NO;
        return;
        
    }
    
    if ([isBindedStr isEqualToString:@"0"])
    {
        if (!kIsIphone)
        {
            UIAlertView *signUpAlertView = [[UIAlertView alloc] initWithTitle:@"检测到您的设备不具备短信和运营商电话功能,请使用iPhone体验本程序~"
                                                                      message:nil
                                                                     delegate:self
                                                            cancelButtonTitle:@"知道了"
                                                            otherButtonTitles:nil, nil];
            
            [signUpAlertView show];
            userEnable = NO;
            return;
        }
        else
        {
            UIAlertView *signUpAlertView = [[UIAlertView alloc] initWithTitle:@"手机注册"
                                                                      message:@"为了您的交易安全,请发送一条短信,完成注册"
                                                                     delegate:self
                                                            cancelButtonTitle:@"稍后再试"
                                                            otherButtonTitles:@"发送短信", nil];
            
            signUpAlertView.tag = kUserLogInAlert;
            [signUpAlertView show];
            userEnable = NO;
            return;
        }
    }
    userEnable = YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int i = alertView.tag;
    switch (i)
    {
        case kUserLogInAlert:
        {
            if (buttonIndex == 1)
            {
                NSString *str1 = [GetPhoneInfo getCurrentTimeStamp];
                NSString *str2 = [GetPhoneInfo getCurrentIMSI];
                NSString *contentStr = [NSString stringWithFormat:@"CODE=ETAXI,TYPE=PASSENGER,TIMESTAMPS=%@,IMSI=%@",str1,str2];
                
                NSString *teleNoStr = nil;
                if ([PassValueClass sharedIntance].messageGatewayNoStr != nil)
                {
                    teleNoStr = [PassValueClass sharedIntance].messageGatewayNoStr;
                }
                else
                {
                    teleNoStr = kSignUpNo;
                }
                NSArray *arrry = [NSArray arrayWithObject:teleNoStr];

                NSLog(@"%@",arrry);

                [self sendSMS:contentStr recipientList:arrry];
                
                MBProgressHUD *HD = [[MBProgressHUD alloc] initWithView:self.view];
                [self.view addSubview:HD];
                HD.labelText = @"正在注册,请耐心等待!";
                [HD showAnimated:YES whileExecutingBlock:^{
                    //对话框显示时需要执行的操作
                    sleep(10);
                } completionBlock:^{[HD removeFromSuperview];}];
            }
        }
            break;
        default:
            break;
    }
}

#pragma mark - SendMMS - 发送短信

- (void)sendSMS:(NSString *)bodyOfMessage recipientList:(NSArray *)recipients
{
    MFMessageComposeViewController *controller = [[MFMessageComposeViewController alloc] init];
    if([MFMessageComposeViewController canSendText])
    {
        controller.body = bodyOfMessage;
        controller.recipients = recipients;
        controller.messageComposeDelegate = self;
        [self presentModalViewController:controller animated:YES];
    }
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissModalViewControllerAnimated:YES];
    
    if (result == MessageComposeResultCancelled)
        NSLog(@"Message cancelled");
    else if (result == MessageComposeResultSent)
        NSLog(@"Message sent");
    else
        NSLog(@"Message failed");
}

/*
 #pragma mark - addDataToArray - 数据源加入数组中
 
 - (void)addDataToArray
 {
 _dataArray = [NSArray arrayWithObjects:@"手机绑定",@"昵称",@"性别",@"可见范围", nil];
 }
 
 #pragma mark - TableView DataSource - 数据源
 
 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView//区间数
 {
 return 1;
 }
 
 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
 return 52;
 }
 
 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section//每个区间的个数
 {
 int i = 0;
 if (_dataArray.count > 0) {
 i = _dataArray.count;
 }
 return i;
 }
 
 - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
 {
 NSString *headStr = nil;
 switch (section)
 {
 case 0:
 {
 headStr = @"账号设置";
 return headStr;
 }
 break;
 default:
 return headStr;
 break;
 }
 }
 
 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
 SettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SettingCell"];
 if (!cell) {
 cell = [SettingCell getInstance];
 cell.selectionStyle = UITableViewCellSelectionStyleNone;
 }
 NSString *str = [_dataArray objectAtIndex:indexPath.row];
 cell.nameLbl.text = [NSString stringWithFormat:@"%@",str];
 
 NSString *str2 = [_savedArray objectAtIndex:indexPath.row];
 if (str2 != nil )
 {
 cell.infoTxtField.text = [NSString stringWithFormat:@"%@",str2];
 if (indexPath.row != 3)
 {
 cell.infoTxtField.userInteractionEnabled = NO;
 }
 }
 
 int i = indexPath.row;
 switch (i)
 {
 case 0:
 {
 if (str2 != nil)
 {
 [cell.infoImgView setImage:[UIImage imageNamed:@""]];
 }
 else
 {
 [cell.infoImgView setImage:[UIImage imageNamed:@""]];
 }
 }
 break;
 case 1:
 {
 
 }
 break;
 case 2:
 {
 
 }
 break;
 case 3:
 {
 
 }
 break;
 
 default:
 break;
 }
 return cell;
 }
 */

@end
